# === 工具链配置 ===
CROSS = riscv64-unknown-elf
CC = $(CROSS)-gcc
LD = $(CROSS)-ld
OBJCOPY = $(CROSS)-objcopy
CFLAGS = -O0 -Wall -fno-pic -ffreestanding -fno-common -mno-relax -mabi=lp64 -march=rv64g -mcmodel=medany
LDFLAGS = -T kernel.ld -nostdlib -z max-page-size=4096

# === 所有源码文件（除了无用的 *.jpg *.md .vscode）===
SRCS = entry.S trap.S userret.S \
       main.c start.c syscall.c sysfile.c uart.c user_main.c user.c kalloc.c string.c

# === 自动生成的目标文件 ===
OBJS = $(SRCS:.c=.o)
OBJS := $(OBJS:.S=.o)

# === 输出文件名 ===
ELF = kernel.elf
BIN = kernel.bin

# === 默认目标 ===
all: $(BIN)

# === 编译规则 ===
%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

%.o: %.S
	$(CC) $(CFLAGS) -c $< -o $@

# === 链接为可执行 ELF 文件 ===
$(ELF): $(OBJS)
	$(LD) $(LDFLAGS) -o $@ $^

# === 转换为裸机镜像（适用于 QEMU -kernel）===
$(BIN): $(ELF)
	$(OBJCOPY) -O binary $< $@

# === 运行 QEMU 模拟器 ===
run: $(BIN)
	qemu-system-riscv64 -machine virt -nographic -bios none -kernel $(BIN)

# === 清理 ===
clean:
	rm -f *.o *.elf *.bin
